package com.common.service.Impl;

import com.common.service.CURDService;
import com.common.utils.CRUD.DataDelete;
import com.common.utils.CRUD.DataQuery;
import com.common.utils.CRUD.DataSave;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Map;

@Service
public class CURDServiceImpl implements CURDService {

    @Autowired
    private DataQuery dataQuery;

    @Autowired
    private DataSave dataSave;

    @Autowired
    private DataDelete dataDelete;

    @Override
    public ArrayList getToGrid(String tabName,String titles) throws InvocationTargetException, IllegalAccessException {
        ArrayList<Map<String, Object>> result = dataQuery.tableQuery(tabName, titles);
        return result;
    }

    @Override
    public Map getToForm(String tabName,String titles) throws InvocationTargetException, IllegalAccessException {
        Map<String, Object> result= dataQuery.formQuery(tabName,titles);
        return result;
    }

    @Override
    public Map saveTable(String tabName, ArrayList<Map<String,Object>> dataSet) throws InvocationTargetException, IllegalAccessException {
        Map<String, Object> result= dataSave.tableSave(tabName, dataSet);
        return result;
    }

    @Override
    public Map saveForm(String tabName, ArrayList<Map<String,Object>> dataSet) throws InvocationTargetException, IllegalAccessException {
        Map<String, Object> result= dataSave.formSave(tabName, dataSet);
        return result;
    }

    @Override
    public Map dataDelete(String tabName,String titles) throws InvocationTargetException, IllegalAccessException {
        Map<String, Object> result= dataDelete.delete(tabName, titles);
        return result;
    }

    @Override
    public Map<String, Object> userSaveMD5(ArrayList<Map<String,Object>> dataSet) throws InvocationTargetException, IllegalAccessException {
        for(Map<String,Object> tresult:dataSet){
            if(tresult.get("name").equals("password")){
                String password = String.valueOf(tresult.get("values"));
                String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
                tresult.put("values",md5Password);
            }
        }
        Map<String,Object> result = dataSave.tableSave("t_user",dataSet);

        return result;
    }


}
